/*
 * @Author: jiu yin
 * @Date: 2025-03-05 19:12:45
 * @LastEditTime: 2025-08-19 15:40:52
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \one-half-vue3-2025-3-7\src\utils\request.js
 */


import axios from "axios";
import { getToken } from "@/utils/auth";


// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // 内部token
    const token = getToken();
    config.headers = {
      Authorization: `Bearer ${token}`,
      "Content-Type": "application/json",
      ...config.headers
    };
    return config;
  },
  error => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    if (res.code == 200) {
      return Promise.resolve(res);
    } else {
      if (res.code === 422 || res.code === 400) {
        message.error(res.message || "服务错误");
        return Promise.reject(new Error(res.message || "Error"));
      } else if (res.code === 401) {
        message.error("登录过期，请重新登录", [ 1 ], () => (window.location.pathname = "/login"));
        return Promise.reject(new Error(res.message || "Error"));
      } else if (res.code === 402) {
        message.error("此账号已被封禁", [ 1 ], () => (window.location.pathname = "/login"));
        return Promise.reject(new Error(res.message || "Error"));
      } else if (typeof res === "string" || res == undefined) {
        message.error("响应错误");
        return Promise.reject(new Error(res || "Error"));
      } else {
        return Promise.resolve(res);
      }
    }
  },
  error => {
    if (error.response?.status === 401 || error.response?.status === 400) {
      // token 过期了
      // 1、重置用户的状态
      // 2、用户跳转到 登录界面
      message.error(error.response.data.msg);
    } else if (error.toString().includes("canceled")) {
      console.info("终止上一次请求");
    } else {
      message.error("服务异常,请稍后重试");
    }
    // return error
    return Promise.reject(new Error(error || "Error"));
  }
);


const request = val => {
  let { data, url, method, ContentType, responseType, type, hasToken, cancelToken, baseURL, onDownloadProgress, timeout } = val;
  if (method == "get" || method == "GET") {
    return service({
      baseURL,
      url,
      method,
      params: data,
      ContentType,
      responseType,
      cancelToken,
      onDownloadProgress,
      timeout
    });
  } else {
    return service({
      baseURL,
      url,
      method,
      data,
      ContentType,
      hasToken,
      responseType,
      cancelToken,
      onDownloadProgress,
      timeout
    });
  }
};

export default request;
